package cc.catface.base.net.core;

import android.app.ProgressDialog;
import android.content.Context;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import javax.net.ssl.SSLHandshakeException;

import cc.catface.commom.context.net.tool.TNetwork;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/** rx */
public abstract class BizObserver<T> implements Observer<BaseResponse<T>> {
    public static final String TAG = "BizObserver";

    /** 服务端code */
    public interface BizCode {
        String SUCCESS = "200";
    }

    private Context mContext;
    private ProgressDialog mDialog;
    private Disposable mDisposable;

    public BizObserver() { }

    public BizObserver(Context context) {
        mContext = context;
    }

    @Override
    public void onSubscribe(@NonNull Disposable disposable) {
        RetrofitHelper.d(TAG + ".onSubscribe(), disposable:" + disposable);
        mDisposable = disposable;
        if (TNetwork.isNetAvail() && disposable.isDisposed()) {
            disposable.dispose();
        }
        if (mDialog == null && mContext != null) {
            mDialog = new ProgressDialog(mContext);
            mDialog.setMessage("正在请求数据...");
            mDialog.show();
        }
    }

    @Override
    public void onNext(BaseResponse<T> response) {
        RetrofitHelper.d(TAG + ".onNext(), response:" + new Gson().toJson(response));
        if (response.getCode().equals(BizCode.SUCCESS)) {//请求成功且业务成功
            onSuccess(response.getData());
            return;
        }
        onFailure(response.getCode(), response.getMessage());//请求成功但业务失败
    }

    @Override
    public void onComplete() {
        dismissDialog();
    }

    @Override
    public void onError(@NonNull Throwable e) {
        RetrofitHelper.d(TAG + ".onError(), e:" + e);
        dismissDialog();
        onFailure("-1", transException(e));
    }

    public void dismissDialog() {
        if (mDisposable != null && mDisposable.isDisposed()) mDisposable.dispose();
        if (null != mDialog && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        mDialog = null;
    }


    /** 请求结果回调 */
    public void onSuccess(T data) { }

    public void onFailure(String code, String message) { }

    //取消订阅
    public void cancelDispose() {
        RetrofitHelper.d(TAG + ".cancelDispose(), 主动取消订阅请求mDisposable:" + mDisposable);
        if (null != mDisposable && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }


    /** 常见请求异常错误信息转换 */
    public static String transException(Throwable e) {
        String error;
        if (e instanceof UnknownHostException) {
            error = "网络连接异常，请检查网络";
        } else if (e instanceof SocketTimeoutException) {
            error = "请求网络超时";
        } else if (e instanceof ParseException || e instanceof JSONException || e instanceof JsonSyntaxException) {
            error = "数据解析错误";
        } else if (e instanceof SSLHandshakeException) {
            error = "网络请求异常，请检查网络";
        } else if (e instanceof HttpException) {
            error = convertStatusCode((HttpException) e);
        } else {
            error = "网络连接异常，请检查网络";
        }
        return error;
    }

    private static String convertStatusCode(HttpException httpException) {
        String error;
        if (httpException.code() >= 500 && httpException.code() < 600) {
            error = "服务器处理请求错误";
        } else if (httpException.code() >= 400 && httpException.code() < 500) {
            error = "服务器无法处理请求";
        } else if (httpException.code() >= 300 && httpException.code() < 400) {
            error = "当前请求已被重定向";
        } else {
            error = httpException.message();
        }
        return error;
    }
}